<template>
  <div class="userinfo-page">
    <!-- Header Cover Image -->
    <div class="header-cover" @click="triggerCoverUpload">
      <input type="file" id="cover" @change="uploadCover" style="display: none;" />
      <img :src="coverUrl" alt="Cover Image" title="点击更换封面"/>
    </div>
    
    <!-- Avatar Upload -->
    <div class="avatar-upload" @click="triggerAvatarUpload">
      <input type="file" id="avatar" @change="uploadAvatar" style="display: none;" />
      <img :src="avatarUrl" alt="Avatar" title="点击更换头像"/>
    </div>

    <!-- Registration Form -->
    <el-row>
      <label><span class="xin">*</span>昵称</label>
    </el-row>
    <el-row>
      <el-input v-model.trim="form.nickname" required placeholder="请输入昵称"/>
    </el-row>

    <el-row v-if="!isUpdate">
      <label><span class="xin">*</span>手机号</label>
    </el-row>
    <el-row v-if="!isUpdate">
      <el-input v-model.trim="form.mobile" required placeholder="请输入手机号" style="width: 50%;margin-right: 10px;">
        <template #append>
          <el-button @click="sendVerificationCode" :disable="countdown > 0">{{ countdown > 0 ? `${countdown}s` : '获取验证码' }}</el-button>
        </template>
      </el-input>
      
    </el-row>

    <el-row v-if="!isUpdate">
      <label><span class="xin">*</span>验证码</label>
    </el-row>
    <el-row v-if="!isUpdate">
      <el-input v-model.trim="form.code" required placeholder="请输入验证码"/>
    </el-row>

    <el-row>
      <label><span class="xin" v-if="!isUpdate">*</span>密码</label>
    </el-row>
    <el-row>
      <el-input v-model.trim="form.password" @input="validatePassword" required placeholder="请输入密码"/>
    </el-row>

    <el-row>
      <label>个性签名</label>
    </el-row>
    <el-row>
      <el-input type="textarea" v-model.trim="form.remark" placeholder="请输入个性签名"/>
    </el-row>

    <el-row>
      <label>性别</label>
    </el-row>
    <el-row>
      <el-select v-model.trim="form.sex" placeholder="请选择性别">
        <el-option label="男" :value="1"></el-option>
        <el-option label="女" :value="2"></el-option>
        <el-option label="其他" :value="0"></el-option>
      </el-select>
    </el-row>

    <el-row>
      <label>生日</label>
    </el-row>
    <el-row>
      <el-date-picker v-model.trim="form.birthday" type="date" value-format="YYYY-MM-DD" placeholder="请选择生日" style="width: 180px;"></el-date-picker>
    </el-row>

    <el-row>
      <label><span class="xin">*</span>所在地（省/市）</label>
    </el-row>
    <el-row>
      <el-select v-model="provinceId" value-key="id" placeholder="请选择省/市" v-if="provinceList.length>0" filterable clearable @change="getLeaf" style="width: 180px; margin-right: 16px;">
        <el-option v-for="item in provinceList" :key="item.id" :label="item.name" :value="item"></el-option>
      </el-select>
      <el-select v-model="cityId" value-key="id" placeholder="请选择所在市" filterable clearable style="width: 180px;" v-if="cityList.length>0">
        <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item"></el-option>
      </el-select>
    </el-row>

    <el-row>
      <label>详细地址</label>
    </el-row>
    <el-row>
      <el-input v-model.trim="form.address" placeholder="除省市外的详细地址"/>
    </el-row>
    <div style="display: flex;align-items: baseline;">
      <el-button class="red-btn" size="large" round @click="submitForm">{{ isUpdate ? '修改' : '注册'}}</el-button>
      <el-button class="gray-btn" size="large" round @click="router.back()">取消</el-button>      
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useLoginStore } from '../api/store';

import emitter from '../utils/eventBus';
import { upload, getProvince, register, sendSms, modifiyUserInfo } from '../api/pcApi';

const router = useRouter();
const props = defineProps({
  isUpdate: {
    type: Boolean,
    default: false   // 提供一个默认值，如果父组件没有传递该参数
  }
});

// 响应式数据
const coverUrl = ref('https://cn.bing.com/th?id=OHR.WhiteSandsNP_ZH-CN2517618394_1920x1080.webp&qlt=50');
const avatarUrl = ref('https://miaocode-ai.oss-ap-southeast-1.aliyuncs.com/gt/storage/2025-01-23/id_0c983f80b0794d90bc4d0337c5ec1cba_file_default_avatar_1.jpg');
const provinceId = ref(null);
const cityId = ref(null);
const form = ref({
  cover: '',
  avatar: '',  
  nickname: '',
  userName: '',
  mobile: '',
  password: '',
  code: '',
  remark: '',
  sex: 1,
  birthday: '',
  provinceId: '',
  cityId: '',
  address: '',  
});

const validatePassword = () => {
  const password = form.value.password;
  const chineseRegex = /[\u4e00-\u9fa5]/;
  if (chineseRegex.test(password)) {
    ElMessage.error('密码不能包含汉字')
    form.value.password = ''
    return false;
  }
}

const countdown = ref(0);
const sendVerificationCode = () => {
  if (!form.value.mobile) {
    ElMessage.error('请输入手机号');
    return;
  }
  if (countdown.value > 0) return

  sendSms({mobile:form.value.mobile}).then(() => {
    ElMessage.success('验证码已发送');
    startCountdown(60)
  }).catch((err) => {
    ElMessage.error(err);
  });
}

const startCountdown = (seconds) => {
  countdown.value = seconds
  const interval = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(interval);
      countdown.value = 0; // 确保倒计时结束后countdown为0
    }
  }, 1000)
}

const provinceList = ref([]);
const cityList = ref([]);
const getProvinceData = (level, pid) => {
  return getProvince(level, pid).then(res => {
    return res || []
  }).catch(err => {
    console.log(err)
    return []
  });
};

const getLeaf = (value) => {
  cityList.value = []
  cityId.value = '';
  return getProvinceData(value?.level+1, value?.id).then(res => {
    cityList.value = res || []
  }).catch(err => {
    console.log(err)
  });
};


const triggerCoverUpload = () => {
  document.getElementById('cover').click();
};

const uploadCover = (event) => {
  const file = event.target.files[0];
  if (file) {
    coverUrl.value = URL.createObjectURL(file);
    const formData = new FormData();
    formData.append('file', file);
    getFileUrl(formData, 'cover');
  }
};

const uploadAvatar = (event) => {
  const file = event.target.files[0];
  if (file) {
    avatarUrl.value = URL.createObjectURL(file);
    const formData = new FormData();
    formData.append('file', file);
    getFileUrl(formData, 'avatar');
  }
};

const getFileUrl = (formData, type) => { 
  upload(formData).then(res => {
    if(type === 'avatar'){
      form.value.avatar = res;
    }
    if(type === 'cover'){
      form.value.cover = res;
    }
  }).catch(error => {
    ElMessage.error(error.message || '上传失败');
    return null
  });
};

const triggerAvatarUpload = () => {
  document.getElementById('avatar').click();
};

const submitForm = () => {
  if (!form.value.nickname) {
    ElMessage.error('请输入昵称');
    return;
  }
  if (!form.value.mobile) {
    ElMessage.error('请输入手机号');
    return;
  }
  if (!form.value.mobile.match(/^1[3-9]\d{9}$/)) {
    ElMessage.error('请输入正确的手机号');
    return;
  }
  if(props.isUpdate){
    
  } else {
    if (!form.value.password) {
      ElMessage.error('请输入密码');
      return;
    }
    if (!form.value.code) {
      ElMessage.error('请输入验证码');
      return;
    }
  }  
  
  if (!provinceId.value || !cityId.value) {
    ElMessage.error('请选择所在地区');
    return;
  }
  form.value.avatar = form.value.avatar || avatarUrl.value;
  form.value.cover = form.value.cover || coverUrl.value;
  form.value.userName = form.value.nickname;
  form.value.provinceId = provinceId.value?.id;
  form.value.cityId = cityId.value?.id;
  if (props.isUpdate) { // 编辑个人信息
    delete form.value.params;    
    return modifiyUserInfo(form.value).then(res => {
      ElMessage.success('修改成功');
      useLoginStore().fetchUserInfo();
      router.go(-1);
    }).catch(err => {
      ElMessage.error(err);
    });
  } else { // 注册账号
    register(form.value).then(res => {
      ElMessage.success('注册成功');
      router.go(-1);
      emitter.emit('open-auth-modal')   
    }).catch(err => {
      ElMessage.error(err);
    });
  }
};

onMounted(async() => {
  try {
    provinceList.value = await getProvinceData(1,100000)
    if (props.isUpdate) { // 编辑个人信息时，获取当前用户信息并填充表单
      form.value = JSON.parse(window.localStorage.getItem('login')).userinfo
      coverUrl.value = form.value.cover
      avatarUrl.value = form.value.avatar
      provinceId.value = provinceList.value.find(item => item.id === form.value.provinceId)
      await getLeaf(provinceId.value)
      cityId.value = cityList.value.find(item => item.id === form.value.cityId)
    }
  } catch (error) {

  }
});
</script>

<style lang="less" scoped>
.userinfo-page {
  width: 1160px;
  margin: 0 auto;
  padding-bottom: 180px;

  .header-cover {
    width: 100%;
    cursor: pointer;
    height: 220px;
    background-color: #eee;
    img {
      width: 100%;
      height: 220px;      
      object-fit: cover;
    }
  }

  .avatar-upload {
    width: 100%;
    text-align: left;
    margin-left: 20px;
    margin-top: -40px;
    img {
      width: 155px;
      height: 155px;
      background-color: #eee;
      border-radius: 50%;
      border: 12px solid #F3F3F3;
      cursor: pointer;
    }
  }

  .el-row {
    width: 100%;
    margin-bottom: 15px;
    label {
      font-weight: 600;
    }
  }

  .red-btn {
    border-color: #A30000;
    background-color: #A30000;
    color: white;
    width: 50%;
    &:hover {
      border-color: #A30000;
    }
  }
  .gray-btn {
    width: 50%;
    margin-left: 16px;
    &:hover {
      background-color: #fff;
      border-color: #A30000;
      color: #000;
    }
  }
  .xin {
    color: red;
    margin-right: 3px;
  }
}
</style>
